
<!--
    /**
     * 树形下拉选择组件，下拉框展示树形结构，提供选择某节点功能，方便其他模块调用
     * 调用示例：
     * <tree-select :height="400" // 下拉框中树形高度
     *              :width="200" // 下拉框中树形宽度
     *              v-model="value"  // 绑定的值
     *              :disabled = false
     *              size="small"  // 输入框的尺寸: medium/small/mini
     *              :data="data" // 树结构的数据
     *              :defaultProps="defaultProps" // 树结构的props
     *              multiple   // 多选
     *              clearable  // 可清空
     *              placeholder="placeholder"   // 默认提示语
     *              checkStrictly // 多选时，严格遵循父子不互相关联
     *              :nodeKey="nodeKey"   // 绑定nodeKey，默认绑定'id'
     *              :index="i"   // 标记
     *              :checkedKeys="defaultCheckedKeys"  // 传递默认选中的节点key组成的数组
     *              @popoverHide="popoverHide"> // 事件有两个参数：第一个是所有选中的节点ID，第二个是所有选中的节点数据
     *              </tree-select>
     */
-->
<template>
  <div>
    <div class="mask" v-show="isShowSelect" @click="isShowSelect = !isShowSelect"></div>
    <el-popover placement="bottom-start" :width="width" trigger="manual" v-model="isShowSelect" @hide="popoverHide">
      <div>
        <el-input class="tree-search-input" v-if="filterable" placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
        <el-tree
          class="common-tree"
          :style="style"
          ref="tree"
          :data="data"
          :props="defaultProps"
          :show-checkbox="multiple"
          :node-key="nodeKey"
          :check-strictly="checkStrictly"
          default-expand-all
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          :highlight-current="true"
          @node-click="handleNodeClick"
          @check-change="handleCheckChange"
          v-bind:data-index="index"
        ></el-tree>
      </div>
      <el-select
        :style="selectStyle"
        slot="reference"
        ref="select"
        :size="size"
        :placeholder="placeholder"
        v-model="selectedData"
        :disabled="disabled"
        :multiple="multiple"
        :clearable="clearable"
        @clear="clearSelected"
        @click.native="disabled ? false : (isShowSelect = !isShowSelect)"
        class="tree-select"
        popper-class="my-tree-select-pop"
      >
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </el-popover>
  </div>
</template>
 
<script>
export default {
  name: 'tree-select',
  props: {
    // 树结构数据
    data: {
      type: Array,
      default() {
        return []
      },
    },
    defaultProps: {
      type: Object,
      default() {
        return {}
      },
    },
    // 配置是否可多选
    multiple: {
      type: Boolean,
      default() {
        return false
      },
    },
    // 配置是否可以清空
    clearable: {
      type: Boolean,
      default() {
        return false
      },
    },
    nodeKey: {
      type: String,
      default() {
        return 'id'
      },
    },
    // 显示复选框情况下，是否严格遵循父子不互相关联
    checkStrictly: {
      type: Boolean,
      default() {
        return false
      },
    },
    // 默认选中的节点key数组
    checkedKeys: {
      type: Array,
      default() {
        return []
      },
    },
    size: {
      type: String,
      default() {
        return ''
      },
    },
    width: {
      type: Number,
      default() {
        return 250
      },
    },
    height: {
      type: Number,
      default() {
        return 300
      },
    },
    placeholder: {
      type: String,
      default() {
        return '请选择'
      },
    },
    filterable: {
      type: Boolean,
      default() {
        return false
      },
    },
    index: {
      type: String,
      default() {
        return ''
      },
    },
    // 配置是否禁用
    disabled: {
      type: Boolean,
      default() {
        return false
      },
    },
    nodeClickable: {
      type: Function,
      default: function () {
        return true
      },
    },
  },
  data() {
    return {
      isShowSelect: false, // 是否显示树状选择器
      options: [],
      selectedData: [], // 选中的节点
      style: 'width:' + this.width + 'px;' + 'height:' + this.height + 'px;',
      selectStyle: 'width:' + (this.width + 24) + 'px;',
      checkedIds: [],
      checkedData: [],
      filterText: '',
      prevSelectData: [], // 前一个选中的节点
    }
  },
  mounted() {
    // this.$nextTick(() => {
    this.initCheckedData()
    // })
  },
  methods: {
    focus() {
      this.$refs.select.focus()
      this.isShowSelect = true
    },
    blur() {
      this.isShowSelect = false
      this.$refs.select.blur()
    },
    initCheckedData() {
      if (this.multiple) {
        if (this.checkedKeys.length > 0) {
          // 勾选上传进来的节点
          this.$refs.tree.setCheckedKeys(this.checkedKeys)
        } else {
          // 清空所有勾选
          var checkedKeys = this.$refs.tree.getCheckedKeys() // 所有被选中的节点的 key 所组成的数组数据
          for (let i = 0; i < checkedKeys.length; i++) {
            this.$refs.tree.setChecked(checkedKeys[i], false)
          }
        }
      } else {
        if (this.checkedKeys.length > 0) {
          // 选中传进来的节点
          var item = this.checkedKeys[0]
          this.$refs.tree.setCurrentKey(item)
          var node = this.$refs.tree.getNode(item)
          if (node) this.selectedData = node.label
          this.prevSelectData = item
        } else {
          // 清空选中
          this.selectedData = ''
          this.$refs.tree.setCurrentKey(null)
        }
      }
    },
    popoverHide() {
      if (this.multiple) {
        this.checkedIds = this.$refs.tree.getCheckedKeys() // 所有被选中的节点的 key 所组成的数组数据
        this.checkedData = this.$refs.tree.getCheckedNodes() // 所有被选中的节点所组成的数组数据
      } else {
        this.checkedIds = this.$refs.tree.getCurrentKey()
        this.checkedData = this.$refs.tree.getCurrentNode()
      }
      this.$emit('popoverHide', this.checkedIds, this.checkedData)
      this.$emit('input', this.checkedIds)
    },
    // 节点被点击时的回调,返回被点击的节点数据
    handleNodeClick(data, node, item) {
      if (!this.nodeClickable(data)) return
      if (!this.multiple && !data.disabled) {
        let tmpMap = {}
        tmpMap.value = node.key
        tmpMap.label = node.label
        this.options = []
        this.options.push(tmpMap)
        this.selectedData = node.label
        this.isShowSelect = !this.isShowSelect
        // 替换记录的前一个选择值
        this.prevSelectData = node.key
      } else if (!this.multiple && data.disabled) {
        this.$refs.tree.setCurrentKey(this.prevSelectData)
      }
      this.$emit('node-click', data, node, item)
      this.$refs.select.focus()
    },
    // 节点选中状态发生变化时的回调
    handleCheckChange() {
      var checkedKeys = this.$refs.tree.getCheckedKeys() // 所有被选中的节点的 key 所组成的数组数据
      this.options = checkedKeys.map((item) => {
        var node = this.$refs.tree.getNode(item) // 所有被选中的节点对应的node
        let tmpMap = {}
        tmpMap.value = node.key
        tmpMap.label = node.label
        return tmpMap
      })
      this.selectedData = this.options.map((item) => {
        return item.label
      })
    },
    // filterNode(value, data) {
    //   if (!value) return true;

    //   return data[this.defaultProps.label].indexOf(value) !== -1;
    // },
    filterNode(value, data, node) {
      if (!value) {
        return true
      }
      let level = node.level
      let _array = [] // 这里使用数组存储 只是为了存储值。
      this.getReturnNode(node, _array, value)
      let result = false
      _array.forEach((item) => {
        result = result || item
      })
      return result
    },
    getReturnNode(node, _array, value) {
      let isPass =
        node.data &&
        node.data[this.defaultProps.label] &&
        node.data[this.defaultProps.label].indexOf(value) !== -1
      isPass ? _array.push(isPass) : ''
      if (!isPass && node.level != 1 && node.parent) {
        this.getReturnNode(node.parent, _array, value)
      }
    },
    // 清空已选择的选项
    clearSelected() {
      if (this.multiple) {
        this.$refs.tree.setCheckedKeys([])
      } else {
        this.$refs.tree.setCurrentKey(null)
      }
      this.checkedIds = []
      this.checkedData = []
      this.selectedData = ''
    },
  },
  watch: {
    isShowSelect(val) {
      // 隐藏select自带的下拉框
      // this.$refs.select.blur();
    },
    checkedKeys(val) {
      if (!val) return
      this.checkedKeys = val
      this.initCheckedData()
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    },
  },
}
</script>
 
<style scoped>
.mask {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  opacity: 0;
  z-index: 10;
}
.common-tree {
  overflow: auto;
}
</style>
 
<style>
.my-tree-select-pop {
  display: none !important;
}
.tree-search-input {
  margin-bottom: 10px;
}
.tree-select .el-select__tags .el-tag .el-tag__close {
  display: none;
}
.tree-select .el-select__tags .el-tag .el-icon-close {
  display: none;
}
.el-tree .el-tree-node .el-tree-node__content .el-checkbox {
  margin-bottom: 0;
}
</style>
